package top.jacktgq.sxt.bio.ChatRoom.version5.client;

import top.jacktgq.sxt.bio.ChatRoom.version5.utils.ResourceUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * @Author CandyWall
 * @Date 2019/10/22--20:45
 * @Description 客户端发送消息线程:
 *                  封装功能：
 *                      1、发送消息
 *                      2、从控制台获取输入消息
 *                      3、释放资源
 *                      4、重写了run方法
 */
public class Send implements Runnable {

    private BufferedReader console;
    private Socket client;
    private DataOutputStream dos;
    private Boolean isRunning;
    public Send(Socket client) {
        this.client = client;
        try {
            console = new BufferedReader(new InputStreamReader(System.in));
            dos = new DataOutputStream(client.getOutputStream());
            isRunning = true;
        } catch (IOException e) {
            e.printStackTrace();
            release();
        }
    }

    //从控制台获取消息
    private String getStrFromConsole() {
        String msg = null;
        try {
            msg = console.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            release();
        }
        return msg;
    }

    //释放资源
    private void release() {
        //停止本次与客户端的通信（接收消息和发送消息）
        this.isRunning = false;
        ResourceUtils.close(dos, client);
    }

    @Override
    public void run() {
        while (isRunning) {
            send();
        }
    }

    //发送消息
    private void send() {
        try {
            System.out.print("请输入用户名：");
            String username = getStrFromConsole();
            System.out.print("请输入密码：");
            String password = getStrFromConsole();
            //过滤掉空字符串
            if (!"".equals(username) && !"".equals(password)) {
                dos.writeUTF("username=" + username + "&password=" + password);
                dos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
            release();
        }
    }
}
